from ImgSrc import get_photos_from_album
import urllib2,os,sys

def download_album(user,aid,password=""):
    """ Dowloads all photos from a given album.
        and save them in a directory named after the album id.
    """
    photos = get_photos_from_album(user,aid,password="")
    print "Downloading photos..."
    if not os.path.exists(aid):
        os.mkdir(aid)
    for name,url in photos :
        ubase,uext = os.path.splitext(url) # find extension
        nbase,next = os.path.splitext(name)
        name = nbase+uext # they convert all image to '.jpg'
        try :
            image = urllib2.urlopen(url)     # download file
            ifname = os.path.normpath(aid+"/"+name) # build destination file name
            ifile = open(ifname,'w')           # open new file
            ifile.write(image.read())          # write it
            ifile.close()                      # and close it
        except urllib2.HTTPError :
            print "Image not found : %s (%s)"%(name,url)

def main():
    
    args = sys.argv[1:]
    nargs = len(args)
    if nargs != 2 and nargs != 3 :
        print "usage : python dl.py user album_id [password]"
        sys.exit(-1)
  
    try :
	    user,album_id,password = args
    except ValueError :
	    user,album_id = args
	    password = ""
    download_album(user,album_id,password)

if __name__ == '__main__' : main()
